<!--
 * @Descripttion: 交易设置
 * @Author: xiao li
 * @Date: 2020-09-28 15:24:24
 * @LastEditors: xiao li
 * @LastEditTime: 2023-01-28 17:03:54
-->
<template>
  <div class="lb-system-transaction">
    <top-nav />
    <div class="page-main">
      <lb-tips>
        未单独设置车费的城市，将使用默认的全局设置车费模式，如果有单独设置城市车费，则全局模式失效
      </lb-tips>

      <el-row class="page-top-operate">
        <lb-button type="primary" icon="el-icon-plus" @click="toShowDialog">{{
          $t('menu.SystemCarFeeCityAdd')
        }}</lb-button>
      </el-row>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" fixed></el-table-column>
        <el-table-column
          prop="title"
          label="城市"
          min-width="120"
        ></el-table-column>
        <el-table-column label="起步距离" prop="start_distance" min-width="120">
          <template slot-scope="scope">
            {{ `${scope.row.start_distance} km` }}
          </template>
        </el-table-column>
        <el-table-column label="起步价" prop="start_price" min-width="120">
          <template slot-scope="scope">
            {{ `${scope.row.start_price} 元` }}
          </template>
        </el-table-column>
        <el-table-column label="里程计价" prop="distance_price" min-width="120">
          <template slot-scope="scope">
            {{ `${scope.row.distance_price} 元/km` }}
          </template>
        </el-table-column>
        <el-table-column label="" prop="invented_distance" min-width="120">
          <template slot="header" slot-scope="scope">
            <div>
              虚拟里程
              <lb-tool-tips padding="11"
                >虚拟里程用于
                距离计算短、车费计算少的情况可在后台增加一部分虚拟里程，减少技师损失
                <div class="mt-sm">
                  用户端显示的距离=实际距离+实际距离*虚拟里程百分比
                </div>
              </lb-tool-tips>
            </div>
          </template>
          <template slot-scope="scope">
            {{ `${scope.row.invented_distance} %` }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="是否上架">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="updateItem(scope.row.id, scope.row.status)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="120">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="toShowDialog(scope.row)"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="confirmDel(scope.row.id)"
                >{{ $t('action.delete') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      </lb-page>
      <el-dialog
        :title="
          $t(
            subForm.id
              ? 'menu.SystemCarFeeCityEdit'
              : 'menu.SystemCarFeeCityAdd'
          )
        "
        :visible.sync="showDialog"
        width="550px"
        center
      >
        <el-form
          @submit.native.prevent
          :model="subForm"
          ref="subForm"
          :rules="subFormRules"
          label-width="120px"
        >
          <el-form-item label="城市" prop="selectedOptions">
            <el-cascader
              size="large"
              :options="areaOptions"
              v-model="subForm.selectedOptions"
              @change="handleChange"
              placeholder="请选择城市"
              :props="{ checkStrictly: true }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="起步距离" prop="start_distance">
            <el-input
              v-model="subForm.start_distance"
              placeholder="请输入起步距离"
            >
              <template slot="append">km</template>
            </el-input>
          </el-form-item>
          <el-form-item label="起步价" prop="start_price">
            <el-input v-model="subForm.start_price" placeholder="请输入起步价">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="里程计价" prop="distance_price">
            <el-input
              v-model="subForm.distance_price"
              placeholder="请输入里程计价"
            >
              <template slot="append">元/km</template>
            </el-input>
          </el-form-item>
          <el-form-item label="虚拟里程" prop="invented_distance">
            <el-input
              v-model="subForm.invented_distance"
              placeholder="请输入虚拟里程"
            >
              <template slot="append">%</template>
            </el-input>
            <lb-tool-tips
              >虚拟里程用于 距离计算短、车费计算少
              的情况可在后台增加一部分虚拟里程，减少技师损失
              <div class="mt-sm">
                用户端显示的距离=实际距离+实际距离*虚拟里程百分比
              </div></lb-tool-tips
            >
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { provinceAndCityData } from 'element-china-area-data'
export default {
  data () {
    let checkCityArea = (rule, value, callback) => {
      let { pid } = this.subForm
      let { provinceArr, cityArr } = this
      if (!pid && (value.length === 0 || (value.length < 2 && !provinceArr.includes(value[0] * 1)))) {
        callback(new Error('请选择城市'))
      } else if (pid && (value.length === 1 || (value.length < 3 && !cityArr.includes(value[0] * 1)))) {
        callback(new Error('请选择具体区县'))
      } else {
        callback()
      }
    }
    return {
      areaOptions: provinceAndCityData,
      // 110000 北京
      // 120000 天津
      // 310000 上海
      // 500000 重庆
      // 710000 台湾
      // 810000 香港
      // 820000 澳门
      provinceArr: [110000, 120000, 310000, 500000, 710000, 810000, 820000],
      cityArr: [710000, 810000, 820000],
      loading: false,
      searchForm: {
        page: 1,
        limit: 10,
        name: ''
      },
      tableData: [],
      total: 0,
      subForm: {
        id: 0,
        selectedOptions: [],
        city: '',
        city_code: '',
        distance_free: '',
        distance_price: '',
        start_distance: '',
        start_price: '',
        invented_distance: ''
      },
      subFormRules: {
        selectedOptions: { required: true, validator: checkCityArea, trigger: 'blur' },
        start_distance: { required: true, validator: this.$reg.isFloatNum, trigger: 'blur' },
        start_price: { required: true, validator: this.$reg.isMoney, trigger: 'blur' },
        distance_price: { required: true, validator: this.$reg.isMoney, trigger: 'blur' },
        invented_distance: { required: true, validator: this.$reg.isPercent, trigger: 'blur' }
      },
      showDialog: false
    }
  },
  created () {
    this.getTableDataList()
  },
  methods: {
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async toChange (index) {
      this.searchForm.status = index
      this.getTableDataList(1)
    },
    async getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let { code, data } = await this.$api.service.serviceList(this.searchForm)
      this.loading = false
      if (code !== 200) return
      this.tableData = data.data
      this.total = data.total
    },
    async toShowDialog (item = {}) {
      let data = JSON.parse(JSON.stringify(item))
      let provinceAndCityDataCopy = JSON.parse(JSON.stringify(provinceAndCityData))
      provinceAndCityDataCopy.map(item => {
        console.log(JSON.parse(JSON.stringify(item)))
        if (item.value * 1 === 500000 || [810000, 820000].includes(item.value * 1) || (item.children && item.children.length === 1 && item.children[0].label === '市辖区')) {
          delete item.children
        }
      })

      let arr = ['province_code', 'city_code']
      this.areaOptions = provinceAndCityDataCopy
      data.selectedOptions = []
      arr.map(aitem => {
        if (data[aitem]) {
          data.selectedOptions.push(data[aitem])
        }
      })
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
      this.showDialog = true
    },
    handleChange (e) {
      let provinceArr = [110000, 120000, 310000, 500000]
      let codeArr = {
        110000: 110100,
        120000: 120100,
        310000: 310100,
        500000: 500100
      }
      let province = e[0] || ''
      let city = provinceArr.includes(province) ? codeArr[province] : e && e.length > 1 ? e[1] : ''
      this.subForm.province_code = province
      this.subForm.city_code = city
      this.subForm.province = ''
      this.subForm.city = ''
      this.subForm.title = ''
      this.subForm.lat = ''
      this.subForm.lng = ''
      this.areaOptions.map((item, index) => {
        if (item.value === e[0]) {
          this.subForm.province = item.label
          if (item.children && item.children.length > 0) {
            item.children.map(aitem => {
              if (aitem.value === e[1]) {
                this.subForm.city = aitem.label
              }
            })
          }
        }
      })
    },
    submitForm () {
      this.$refs['subForm'].validate(valid => {
        if (valid) {
          let subForm = JSON.parse(JSON.stringify(this.subForm))
          delete subForm.selectedOptions
          if (!subForm.city || ['市辖区', '县'].includes(subForm.city)) {
            subForm.city = subForm.province
          }
          subForm.title = subForm.area || subForm.city
          let type = subForm.id ? 'cityFeeUpdate' : 'cityFeeAdd'
          this.$api.system[type](subForm).then((res) => {
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successSub'))
              this.showDialog = false
              this.getTableDataList()
            }
          })
        }
      })
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-system-transaction {
  width: 100%;
  .page-main {
    padding: 20px;
    .el-form {
      width: 100%;
      .el-form-item {
        margin-bottom: 24px;
        .el-select,
        .el-input-number,
        .el-cascader,
        .el-input {
          width: 300px;
        }
      }
      .last-form-item {
        margin-top: 30px;
      }
      .item-tips {
        margin-left: 120px;
        margin-bottom: 24px;
        color: #999999;
      }
    }
  }
}
</style>
